import { ArticleDetailResponse } from '@/types/data';
import { RootThunkAction } from '@/types/store';
import { http } from '@/utils/http';

// 导入dayjs
import dayjs from 'dayjs';
// 导入本地化格式插件
import localizedFormat from 'dayjs/plugin/localizedFormat';
dayjs.extend(localizedFormat);

// 获取文章详情
export const getArticleById = (id: string): RootThunkAction => {
  return async (dispatch) => {
    const res = await http.get<ArticleDetailResponse>(`/articles/${id}`);
    console.log('文章详情res', res.data.data);
    // TODO 数据格式转化逻辑

    // 发起action 把数组存储到reducer
    const date = new Date(res.data.data.pubdate);
    const newPubdate =
      date.getFullYear() +
      '/' +
      (date.getMonth() + 1) +
      '/' +
      date.getDate() +
      '/';
    console.log(newPubdate);
    dispatch({
      type: 'article/getArticleById',
      payload: {
        ...res.data.data,
        // pubdate: dayjs(res.data.data.pubdate).locale('zh-cn').format('LL'),
        pubdate: newPubdate,
      },
    });
  };
};

// 关注或取消关注
export const followAuthor = (
  id: string,
  isFollowed: boolean
): RootThunkAction => {
  return async (dispatch) => {
    try {
      // 发起请求
      if (isFollowed) {
        // 取关
        await http.delete(`/user/followings/${id}`);
      } else {
        // 关注
        await http.post('/user/followings', {
          target: id,
        });
      }
      dispatch({
        type: 'article/updateInfo',
        payload: {
          name: 'is_followed',
          value: !isFollowed,
        },
      });
    } catch (error) {
      console.log('提示用户关注/取关失败');
    }
  };
};
